package com.hyf.rabbitmq.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class TopicSend2 {

    private static final String EXCHANGES_NAME="topic_logs";

    public static void main(String[] args){
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("12345");

        Connection connection =null;
        Channel channel=null;
        try {
            connection=connectionFactory.newConnection();
            channel = connection.createChannel();

            channel.exchangeDeclare(EXCHANGES_NAME, BuiltinExchangeType.TOPIC);


            String[] routingKeys=new String[]{" ","..","word"};
            for(String routingKey:routingKeys){
                String message=String.format("From routingKey:%s message!",routingKey);
                channel.basicPublish(EXCHANGES_NAME,routingKey,null,message.getBytes());
                System.out.println(String.format("TopicSend [x] send routingKey:%s,message:%s",routingKey,message));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally{
            if(channel!=null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
